<template>
    <div class="index">
        <div class="model-title">Model:
            机器狗
        </div>
        <!-- <audio controls autoplay ref="audio"></audio> -->
        <div class="chat_container" ref="chat_container_box">
            <div class="chat_t" v-if="false">
                <span>机器狗</span>
                <span> </span>
            </div>
            <ul class="chat_warp" v-resize="onResize" ref="chat_container">
                <!--                <li v-for="(item, index) in voiceChatList" :key="index"-->
                <!--                    :class="item.userRole === UserRole.ME ? 'chat_right' : 'chat_left'">-->
                <!--                    <img v-if="item.userRole === UserRole.Other" class="chat_img" :src="item.headerImg"-->
                <!--                         :alt="item.username">-->
                <!--                    <span class="chat_text" :class="item.userRole === UserRole.ME ? 'chat_right' : 'chat_left'">-->
                <!--                  <span>{{ item.text }}</span>-->
                <!--                </span>-->
                <!--                    <img v-if="item.userRole === UserRole.ME" class="chat_img" :src="item.headerImg"-->
                <!--                         :alt="item.username">-->
                <!--                </li>-->
            </ul>
        </div>
        <div class="footer" @mousedown="changeVoice" @mouseup.native="stopRecording">
            <div class="suffix" v-if="!isLoading">
                <div >
                    <el-icon v-if="audioBtnLoading" :size="20">
                        <Mute/>
                    </el-icon>
                    <el-icon v-else :size="20">
                        <Microphone/>
                    </el-icon>
                </div>
            </div>
            <div class="dog-loading"  v-if="isLoading" style="position: relative">
                <Loading></Loading>
            </div>
            <span class="btn-v" v-if="!isLoading">
                点击录音
            </span>
        </div>
    </div>
</template>

<script setup lang="ts">
import {ref, onMounted, reactive} from 'vue'
import Recorder from 'js-audio-recorder'
import {ElMessage} from 'element-plus'
import md5 from "js-md5";
import {Loading} from "@/components";
import CryptoJS from "crypto-js";
import urlencode from "urlencode";
import wenTou from "@/assets/personal.png";
import wenDa from "@/assets/da.png";
import {upload} from "@/api/contribute";
import {wavToMp3, blobToBase64} from '@/lib/voice'
import headerImg1 from '@/assets/01.jpg'
import headerImg2 from '@/assets/02.jpg'
import headerImg3 from '@/assets/03.jpg'
import headerImg4 from '@/assets/04.jpg'
import headerImg5 from '@/assets/05.jpg'
import headerImg6 from '@/assets/06.jpg'
import headerImg7 from '@/assets/07.jpg'

let dogText = ref<string>('')

enum UserRole {
  ME,
  Other
}

let chat_container = ref<HTMLDivElement>()
let chat_container_box = ref<HTMLDivElement>()
let audio = ref<HTMLAudioElement>()
let recorder = ref<any>()
let audioBtnLoading = ref(false)
let isLoading = ref(false)
let startTime: any;
let endTime: any;
let speechRecognition = ref(new (webkitSpeechRecognition)());
const changeVoice = () => {
  audioBtnLoading.value = true;
  speechRecognition.value.start();
}
const stopRecording = () => {
  audioBtnLoading.value = false;
  speechRecognition.value.stop();
    isLoading.value = true
  let dogInter = setInterval(() => {
      clearInterval(dogInter)
      isLoading.value = false
      if(!dogText.value) {
          return ElMessage.error('请您清晰的再说一遍')
      }
      createMessageList(dogText.value)
      dogText.value = ''
  },1000)

}

const Hmacstr = (e, key) => {
  let result = CryptoJS.HmacSHA1(e, key);
  let sig = result.toString(CryptoJS.enc.Base64);
  sig = encodeURI(sig);
  sig = urlencode(sig);
  return sig;
}

const SecretKey = 'e35e1a8fbee8f46dc2b55ac6571bf69e'
const APPID = '92908e68'
const uploadAudio = async (blob: any) => {
  const timestamp = Date.now();
  let baseString: string;
  baseString = APPID + timestamp.toString()
  baseString = md5(baseString)
  // console.log(baseString)
  let signa = Hmacstr(baseString, SecretKey)
  let duration = endTime - startTime;
  let params = {
    signa,
    fileSize: blob.size,
    duration,
    appid: APPID,
    filename: '帮我转成文本.wav',
    ts: timestamp.toString()
  }
  const result = await upload(params)
  console.log(result)
}

// uploadAudio()


const createMessageList = (aiMsg: string) => {
  let wen = document.createElement('div')
  let wenIms = document.createElement('img')
  let wenSp = document.createElement('span')
  wenIms.setAttribute('src', wenTou)
  wenIms.setAttribute('width', '30px')
  wenIms.style.marginRight = '10px'
  wen.className = 'chat_wen'

  wenSp.innerText = aiMsg
  wen.append(wenIms)
  wen.append(wenSp)
  // let da = document.createElement('div')
  // da.className = 'chat_da'
  // let markDown = document.createElement('div')
  // let svgImg = document.createElement('img')
  // svgImg.className = 'svg-img'
  // svgImg.src = wenDa
  // markDown.className = 'markdown-body'
  // markDown.style.width = '100%'
  // markDown.innerHTML = aiMsg
  // da.append(svgImg)
  // da.append(markDown)
  chat_container.value!.append(wen)
  // chat_container.value!.append(da)
  // return markDown
}


const getContainerHeight = () => {
  let chatContainerHeight = ref<number>((chat_container.value as HTMLDivElement)?.offsetHeight);
  return chatContainerHeight.value
}
const getContainerBoxHeight = () => {
  let chatContainerHeight = ref<number>((chat_container_box.value as HTMLDivElement)?.offsetHeight);
  return chatContainerHeight.value
}
const onResize = () => {
  chat_container_box.value!.scrollTop = (getContainerHeight() - getContainerBoxHeight() + 20)
}
onMounted(() => {

  if (typeof (navigator.mediaDevices.getUserMedia) == "undefined") {
    ElMessage.error('当前没有语音权限！')
    return
  }
  if (!('webkitSpeechRecognition' in window)) {
    ElMessage.error('版本过低，请升级！')
    return
  }
  console.log('**--**', 'speechRecognition.value', speechRecognition.value);
  speechRecognition.value.continuous = true;
  speechRecognition.value.interimResults = true;
  speechRecognition.value.lang = 'cmn-Hans-CN';
  speechRecognition.value.onstart = () => {
  };
  speechRecognition.value.onerror = () => {
  };
  speechRecognition.value.onend = () => {
  };

  speechRecognition.value.onresult = (event) => {
    console.log('**--**', 'event', event);
    // const textInfo = event?.results?.find(v => !!v.isFinal);
    // if (textInfo) {
    //   const text = textInfo?.[0]?.transcript
    //   if (text) {
    //     console.log('**--**', 'text', text);
    //   }
    // }
    var current = event.resultIndex;

    // 获取此前所说话的记录
    var transcript = event.results[current][0].transcript;
    // str+=transcript
    dogText.value = transcript
  };
})
</script>

<style scoped lang="scss">
.dog-loading {
    width: 24px;
    height: 24px;
}
.chat_warp {
  list-style: none;
  margin: 0;
  padding: 0;

  li {
    display: flex;
    align-items: flex-start;
    margin: 15px 0;
    padding: 0 30px;

  }

  .chat_img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    overflow: hidden;
  }

  .chat_text {
    font-size: 20px;
    margin: 0 15px;
    flex: 1;
    min-height: 50px;
    display: flex;
    align-items: center;
  }

  .chat_right {
    justify-content: flex-end;
    padding-left: 40px;
  }

  .chat_left {
    justify-content: flex-start;
    padding-right: 40px;
  }
}

.btn-v {
  font-size: 18px;
    user-select: none;
}

:deep(textarea) {
  resize: none;
  padding-right: 40px;
}

.index {
  //background: rgb(247, 247, 248);
  //background: #fff;
  //height: 100%;
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  //grid-template-rows: calc(100vh - 80px);
  padding: 40px 0 20px;
  //height: calc(100vh - 80px);
  height: 100%;
  justify-content: space-between;
}

.model-title {
  position: absolute;
  width: 100%;
  color: var(--text-color-title);
  padding: 12px;
  background: var(--bg-color-title);
  top: 0;
  left: 0;
  font-size: 16px;
  box-sizing: border-box;
}

:deep(.code-block-wrapper) {
  width: 100%;

  > pre {
    width: 100% !important;
  }
}

.footer {
  //flex-grow: .08;
  background: rgba(255, 255, 255, .2);
  //padding: 13px 37px 13px 57px;
  //height: 0;
  cursor: pointer;
  width: 70%;
  //margin: auto;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, .1);
  //position: relative;
  padding: 10px 10px;
  border-radius: 5px;
  //height: 0;
  //flex-grow: 1;
  font-size: 0;
  display: flex;
  align-items: center;
  justify-content: center;

  &:active {
    background: rgba(0, 0, 0, .2);
  }
}

:deep(.el-textarea) {
  box-shadow: 0 0 0 1px var(--bg-border-input, var(--bg-color-da));
  border-radius: 5px;
  background: var(--bg-input-color);
  padding: 10px 0;
}

.suffix {
  cursor: pointer;
  //position: absolute;
  font-size: 0;
  //right: 20px;
  //top: 32px;
  //transform: translateY(-50%);
}

.chat_container {
  text-align: left;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding-bottom: 20px;
  flex: 1;
  width: 100%;
  //height: 0;
  //flex-grow: 10;
  //flex-grow: 1;
  //height: 0;
  &::-webkit-scrollbar {
    background-color: transparent;
    -webkit-border-radius: 2em;
    -moz-border-radius: 2em;
    border-radius: 2em;
    width: 0;
  }

  &::-webkit-scrollbar-thumb {
    background-color: transparent;
    -webkit-border-radius: 2em;
    -moz-border-radius: 2em;
    border-radius: 2em;
  }
}

:deep(.chat_da) {
  //background: #fff;
  padding: 30px;
  line-height: 27px;
  background: var(--bg-color-da);
  color: var(--text-color-da);
  font-size: 16px;
  display: flex;
  align-items: flex-start;
}

:deep(.svg-img) {
  //background: rgb(16, 163, 127);
  color: #fff;
  flex: 0 0 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  margin-right: 10px;
}

:deep(.chat_wen) {
  padding: 30px;
  line-height: 27px;
  display: flex;
  align-items: center;
  color: var(--text-color-da);
  font-size: 16px;
}

.icon-input {
  color: var(--text-color-da);
}

.chat_t {
  display: flex;
  align-items: center;
  margin: auto;

  span {
    &:nth-child(1) {
      font-size: 36px;
      color: #d9d9e2;
      font-weight: bold;
    }

    &:last-child {
      background: rgb(250, 230, 158);
      color: rgb(146, 114, 1);
      font-size: 14px;
      font-weight: bold;
      padding: 2px 6px;
      border-radius: 6px;
      margin-left: 6px;
    }
  }
}

:deep(.el-textarea__inner) {
  background: var(--bg-input-color);
  box-shadow: none;
  //padding-top: 9px;
  //box-shadow: 0 0 0 1px var(--bg-border-input, var(--bg-color-da));

}

:deep(.el-textarea__inner) {
  color: var(--text-color-da);

}


:deep(.pending) {
  width: 10px;
  height: 20px;
  background: #000;
  animation: peddings 0.5s linear infinite forwards;
}

@keyframes peddings {
  to {
    opacity: 1;
  }
  from {
    opacity: 0;
  }
}

#anchor {
  height: 1px;
  overflow-anchor: auto;
}
</style>
